<template>
  <div>
<el-button type="primary" @click="dialogForm">新增</el-button>
<el-button type="primary" @click="delAll">删除</el-button>
<el-table :data="ProductInfoData" style="width: 100%"  ref="multipleTableRef"  @selection-change="handleSelectionChange">
  <el-table-column type="selection" :selectable="selectable" width="55" />
  <el-table-column type="index" label="序号" width="100" />
 <el-table-column prop="productName" label="商品名称" width="100" />
 <el-table-column prop="productBatch" label="生产批次" width="100" />
 <el-table-column prop="productPeriod" label="保质期" width="100" />
 <el-table-column prop="productLicense" label="生产许可证号" width="100" />
 <el-table-column prop="productEnterprise" label="生产企业" width="150"/>
 <el-table-column prop="productPicture" label="信息完善度" width="150">
  <template #default="{row}">
    <el-image :src="row.productPicture" style="width: 100px; height: 100px" />
  </template>
  </el-table-column>
 <el-table-column prop="createOperatorName" label="创建人" width="150"/>
 <el-table-column prop="createDate" label="创建时间" width="150">
    <template #default="{row}">
    {{ moment(row.createDate).format('YYYY-MM-DD HH:mm:ss') }}
  </template>
  </el-table-column>
 <el-table-column prop="modifyOperatorName" label="修改人" width="150"/>
 <el-table-column  label="操作" >
  <template #default="{row}">
    <el-button type="primary" @click="router.push({path:'/MenuView/ProductDetail',query:{productInfoId:row.productInfoId}})">详情</el-button>
    <el-button type="danger" @click="delProductInfoData(row.productInfoId)">删除</el-button>
    <el-button type="warning" @click="dialogUpForm(row.productInfoId)">编辑</el-button>
    <el-button type="primary" @click="dialogExportFormDialog(row.productInfoId)">导出溯源码</el-button>
  </template>
  </el-table-column>
</el-table>

<table>
  <tr>
    <td>
      <el-pagination
    v-model:current-page="page.PageIndex"
    v-model:page-size="page.PageSize"
    :page-sizes="[1, 2, 3, 5]"
    :background="true"
    layout="slot, sizes"
    :total="page.totalCount"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  >
  共{{ page.totalCount }}条，每页{{ page.PageSize }}条，
  当前第{{ page.PageIndex }}/{{ page.totalPage }}页
  </el-pagination>
    </td>
    <td>
      <el-pagination
    v-model:current-page="page.PageIndex"
    v-model:page-size="page.PageSize"
    :page-sizes="[1, 2, 3, 5]"
    :background="true"
    layout="slot, prev, pager, next"
    :total="page.totalCount"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    prev-text="上一页"
    next-text="下一页"
  >
  <el-button type="primary" @click="handleCurrentChange(1)" :disabled="page.PageIndex==1">首页</el-button>
  </el-pagination>
    </td>
    <td>
      <el-pagination
    v-model:current-page="page.PageIndex"
    v-model:page-size="page.PageSize"
    :page-sizes="[1, 2, 3, 5]"
    :background="true"
    layout="slot, jumper"
    :total="page.totalCount"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  >
  <el-button type="primary" @click="handleCurrentChange(page.totalPage)" :disabled="page.PageIndex==page.totalPage">尾页</el-button>
  </el-pagination>
    </td>
  </tr>
</table>

<!-- 导出溯源码设置 -->
<el-dialog v-model="dialogExportFormVisible" title="导出溯源码设置" width="500">
    <el-form >
      <el-form-item label="导出数量" :label-width="formLabelWidth">
        <el-input v-model="ExportNum" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="exportCode">
          导出
        </el-button>
      </div>
      </template>
      </el-dialog>

<!-- 新增商品信息 -->
<el-dialog v-model="dialogFormVisible" title="新增商品信息" width="500">
  <el-form :model="form">
    <el-form-item label="商品名称" :label-width="formLabelWidth">
      <el-select v-model="form.productName" placeholder="请选择" clearable>
        <el-option v-for="item in ProductData" :label="item.productName" :value="item.productName" />
      </el-select>
    </el-form-item>
    <el-form-item label="生产批次" :label-width="formLabelWidth">
      <el-input v-model="form.productBatch" />
    </el-form-item>
    <el-form-item label="保质期(天)" :label-width="formLabelWidth">
      <el-input v-model="form.productPeriod" />
    </el-form-item>
    <el-form-item label="生产许可证号" :label-width="formLabelWidth">
      <el-input v-model="form.productLicense" />
    </el-form-item>
    <el-form-item label="生产企业" :label-width="formLabelWidth">
      <el-input v-model="form.productEnterprise"  />
    </el-form-item>
    <el-form-item label="封面图" :label-width="formLabelWidth">
   <el-upload
    class="avatar-uploader"
    action="http://localhost:5127/api/UpLoad/UploadFile"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
    </el-form-item>
  </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取消</el-button>
      <el-button type="primary" @click="addProductInfoData">
        新增
      </el-button>
    </div>
  </template>
</el-dialog>

  <!-- 编辑商品信息 -->
  <el-dialog v-model="dialogUpFormVisible" title="编辑商品信息" width="500">
  <el-form :model="upform">
    <el-form-item label="商品名称" :label-width="formLabelWidth">
      <el-select v-model="upform.productName" placeholder="请选择" clearable>
        <el-option v-for="item in ProductData" :label="item.productName" :value="item.productName" />
      </el-select>
    </el-form-item>
    <el-form-item label="生产批次" :label-width="formLabelWidth">
      <el-input v-model="upform.productBatch" />
    </el-form-item>
    <el-form-item label="保质期(天)" :label-width="formLabelWidth">
      <el-input v-model="upform.productPeriod" />
    </el-form-item>
    <el-form-item label="生产许可证号" :label-width="formLabelWidth">
      <el-input v-model="upform.productLicense" />
    </el-form-item>
    <el-form-item label="生产企业" :label-width="formLabelWidth">
      <el-input v-model="upform.productEnterprise"  />
    </el-form-item>
    <el-form-item label="封面图" :label-width="formLabelWidth">
   <el-upload
    class="avatar-uploader"
    action="http://localhost:5127/api/UpLoad/UploadFile"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
    </el-form-item>
  </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="dialogUpFormVisible = false">取消</el-button>
      <el-button type="primary" @click="upProductInfoData">
        确定
      </el-button>
    </div>
  </template>
</el-dialog>
</div>
</template>

<script lang="ts" setup>
import { reactive, ref,onMounted } from 'vue'
import { ElMessage,ElMessageBox } from 'element-plus';
import { useCounterStore } from '@/stores/counter';
const useStore=useCounterStore();
import { useRouter } from 'vue-router';
const router = useRouter();
import { api1, api2 } from '@/main';
import moment from 'moment';
//@ts-ignore
import Cookies from 'js-cookie'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import type { UploadProps } from 'element-plus'
import type { TableInstance } from 'element-plus'

const multipleTableRef = ref<TableInstance>()
const dialogUpFormVisible = ref(false)
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
const imageUrl = ref('')
const selectable = (row: ProductInfo)=> true;
const ProductIds = ref<number[]>([]);

const handleSelectionChange = (val: ProductInfo[]) => {
  //console.log(val);
  ProductIds.value=val.map(item=>item.productInfoId);
  console.log(ProductIds.value);
}
const dialogExportFormVisible=ref(false);
const ExportNum=ref({});
const ProductionId=ref({});
//打开导出溯源码设置对话框
const dialogExportFormDialog=(productInfoId:number)=>{
  dialogExportFormVisible.value=true;
  ProductionId.value=productInfoId;
  ExportNum.value=0;
}

//导出溯源码
const exportCode=()=>{
  api2.get('/api/writeprovenance/Provenance/ExportCode',{
    params:{
      num:ExportNum.value,
      productInfoId:ProductionId.value
    }
  })
  .then(res=>{
    ElMessage.success('已保存为:'+res.data);
    dialogExportFormVisible.value=false;
  })
}

const delAll=()=>{
  let num=ProductIds.value.length;
  if (num === 0) {
    // 如果没有选中任何商品，显示一个不同的消息
    ElMessage.warning('没有选中任何溯源商品进行删除。');
    return; // 退出函数，不执行删除操作
  }

  var ids=ProductIds.value.join(',');
  ElMessageBox.confirm(
  `确定删除已选择的${num}个溯源商品?`,
  'Warning',
  {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }
)
  .then(() => {
    api2.delete('/api/writeprovenance/Provenance/DelRangeProductInfo?ids='+ids)
.then(res=>{
   if(res.data.isSuc)
   {
     ElMessage.success(`已删除选择的${num}个溯源商品`);
     loadData();
   }
   else
   {
     ElMessage.error('删除失败，请稍后再试');
   }
})
  })
}


const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  console.log(response);
  imageUrl.value = response;
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg'&&rawFile.type !== 'image/png') {
    ElMessage.error('图片必须是 jpeg 或者 png 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const form = reactive({
  productName: "",
  productBatch: "",
  productPeriod: 0,
  productLicense: "",
  productEnterprise: "",
  productPicture: ""
})
const dialogForm=()=>{
dialogFormVisible.value=true;
form.productName="";
form.productBatch="";
form.productPeriod=0;
form.productLicense="";
form.productEnterprise="";
form.productPicture="";
}
const addProductInfoData=()=>{
form.productPicture=imageUrl.value;
api2.post('/api/writeprovenance/Provenance/InsertProductInfo',form)
.then(res=>{
  if(res.data.isSuc)
  {
    ElMessage.success(res.data.msg);
    dialogFormVisible.value=false;
    loadData();
  }
  else
  {
    ElMessage.error(res.data.msg);
    dialogFormVisible.value=false;
  }
})
}
const delProductInfoData=(productInfoId:number)=>{
ElMessageBox.confirm(
  '确定删除该溯源商品?',
  'Warning',
  {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }
)
  .then(() => {
    api2.delete('/api/writeprovenance/Provenance/DelProductInfo?ProductInfoId='+productInfoId)
.then(res=>{
   if(res.data.isSuc)
   {
     ElMessage.success('删除成功');
     loadData();
   }
   else
   {
     ElMessage.error('删除失败，请稍后再试');
   }
})
  })
}
const upform=ref({
  productInfoId:0,
  productName: "",
  productBatch: "",
  productPeriod: 0,
  productLicense: "",
  productEnterprise: "",
  productPicture: ""
})
const dialogUpForm=(productInfoId:number)=>{
useStore.productInfoId=productInfoId;
dialogUpFormVisible.value=true;
api1.get('/api/provenance/Provenance/BackProductInfo',{
  params:{
    ProductInfoId:productInfoId
  }
})
.then(res=>{
  upform.value=res.data.data;
  imageUrl.value=res.data.data.productPicture;
})
}
const upProductInfoData=()=>{
upform.value.productPicture=imageUrl.value;
upform.value.productInfoId=useStore.productInfoId;
api2.put('/api/writeprovenance/Provenance/UpdateProductInfo',upform.value)
.then(res=>{
  if(res.data.isSuc)
  {
    ElMessage.success(res.data.msg);
    dialogUpFormVisible.value=false;
    upform.value.productName="";
    upform.value.productBatch="";
    upform.value.productPeriod=0;
    upform.value.productLicense="";
    upform.value.productEnterprise="";
    upform.value.productPicture="";
    loadData();
  }
  else
  {
    ElMessage.error(res.data.msg);
    dialogUpFormVisible.value=false;
    upform.value.productName="";
    upform.value.productBatch="";
    upform.value.productPeriod=0;
    upform.value.productLicense="";
    upform.value.productEnterprise="";
    upform.value.productPicture="";
  }
})
}


interface ProductInfo{
   productInfoId: number,
   productName: string,
   productBatch: string,
   productPeriod: number,
   productLicense: string,
   productEnterprise: string,
   productPicture: string,
   createOperatorName: string,
   createDate: Date,
   modifyOperatorName: string|null
}
const ProductInfoData=ref<ProductInfo[]>([]);
const page=reactive({
PageIndex:1,
PageSize:5,
totalCount:0,
totalPage:0
})

onMounted(()=>{
loadData();
loadProduct();
})
const loadData=()=>{
api1.get('/api/provenance/Provenance/GetProductInfo',{
  params:{
    PageIndex:page.PageIndex,
    PageSize:page.PageSize
  }
})
.then(res=>{
  ProductInfoData.value=res.data.data.data;
  page.totalCount=res.data.data.totalCount;
  page.totalPage=res.data.data.totalPage;
})
}
const handleSizeChange = (val: number) => {
page.PageSize=val;
loadData();
}

const handleCurrentChange = (val: number) => {
page.PageIndex=val;
loadData();
}
const ProductData=ref([{
   productId: 0,
   productName: ""
}])
const loadProduct=()=>{
  api1.get('/api/provenance/Provenance/GetProductList')
.then(res=>{
  ProductData.value=res.data.data;
})
}

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
